package sms

import (
	"cgs-server/helper"
	"cgs-server/server"
	"cgs-server/server/service/sms"
	"net/http"
)

type SmsHandler struct {

}

func NewSmsHandler() *SmsHandler {
	return &SmsHandler{}
}

func (s *SmsHandler) GetValidationCode(w http.ResponseWriter, r *http.Request) {
	phoneNumber := r.FormValue("phoneNumber")
	if valid := helper.CheckPhone(phoneNumber); !valid {
		_, _ = helper.WriteJSON(w, server.Fail("无效的手机号"))
		return
	}
	if err := sms.SendValidationCode(phoneNumber); err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	_, _ = helper.WriteJSON(w, server.OK("发送成功"))
}

func (s *SmsHandler) CheckValidationCode(w http.ResponseWriter, r *http.Request) {
	phoneNumber := r.FormValue("phoneNumber")
	validationCode := r.FormValue("validationCode")
	if valid := helper.CheckPhone(phoneNumber); !valid {
		_, _ = helper.WriteJSON(w, server.Fail("无效的手机号"))
		return
	}
	if err := sms.CheckValidationCode(phoneNumber, validationCode); err != nil {
		_, _ = helper.WriteJSON(w, server.Fail(err.Error()))
		return
	}

	_, _ = helper.WriteJSON(w, server.OK("验证码正确"))
}
